<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               :row-class-name="rowClassName"
               :cell-class-name="rowClassName"
               v-model="form"
               ref="crud"
               @sort-change="sortChange"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button
                type="primary"
                icon="el-icon-plus"
                v-if="permission.purchase_main_add"
                @click="handleAdd"
        >新 增
        </el-button>
        <!--<el-button type="danger"-->
                   <!--icon="el-icon-delete"-->
                   <!--v-if="permission.purchase_main_delete"-->
                   <!--@click="handleDelete">删 除-->
        <!--</el-button>-->
      </template>
      <template #menu-right="{disabled}">
        <div style="float: left; padding-right: 20px;">
          <el-radio-group v-model="query.purchaseStatus" class="list">

            <el-radio label=""  @change="refreshChange">全部</el-radio>
            <el-radio label="未审核"  @change="refreshChange">未审核</el-radio>
            <el-radio label="已审核"  @change="refreshChange">已审核</el-radio>
            <!--<el-radio label="人工关闭"  @change="refreshChange">人工关闭</el-radio>-->
          </el-radio-group>

        </div>
      </template>
      <template #purchaseType-search="{ disabled, size  }">
        <el-select v-model="query.purchaseType"
                   style="width: 100%"
                   :clearable="true"
                   :filterable="true"
                   placeholder="请选择类别"
                   type="string" transfer>
          <el-option
                  v-for="item in typeDict"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictValue"/>
        </el-select>
      </template>
      <template #purchaseDate-search="{ disabled, size }">
        <!--<div style="display: flex;flex-direction: start;">-->
          <!--<el-select v-model="query.purchaseDateRule" placeholder="比较" filterable clearable>-->
            <!--<el-option label="" value=""></el-option>-->
            <!--<el-option value=">" label="大于">大于 </el-option>-->
            <!--<el-option value=">=" label="大于等于">大于等于 </el-option>-->
            <!--<el-option value="=" label="等于">等于 </el-option>-->
            <!--<el-option value="!=" label="不等于">不等于 </el-option>-->
            <!--<el-option value="<=" label="小于等于">小于等于 </el-option>-->
            <!--<el-option value="<" label="小于">小于 </el-option>-->
          <!--</el-select>-->
          <!--<el-date-picker-->
                  <!--size="default"-->
                  <!--v-model="query.purchaseDateSearch"-->
                  <!--type="date"-->
                  <!--:format="dateFormat"-->
                  <!--:value-format="dateFormat"-->
                  <!--:unlink-panels="true"-->
                  <!--clearable-->
                  <!--placeholder="创建日期"-->
                  <!--@change="handleDatePickerChange"-->
                  <!--:picker-options="pickerOptions"-->
          <!--&gt;-->
          <!--</el-date-picker>-->
        <!--</div>-->
        <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.purchaseDateRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="采购日期"
                @change="handleDatePickerChange"
                :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>
      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button
                  icon="el-icon-view"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleView(row)"
                  v-if="permission.purchase_main_view"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="修改" placement="top" v-if="row.purchaseStatus =='未审核'">
          <el-button
                  icon="el-icon-edit"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleEdit(row)"
                  v-if="permission.purchase_main_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="审核" placement="top" v-if="row.purchaseStatus =='未审核'">
          <el-button
                  icon="EditPen"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleAudit(row)"
                  v-if="permission.purchase_main_audit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="反审核" placement="top" v-if="row.purchaseStatus =='已审核'">
          <el-button
                  icon="NoSmoking"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rollbackAudit(row)"
                  v-if="permission.purchase_main_audit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="采购单报表" placement="top">
          <el-button
                  icon="Reading"
                  link
                  :size="size"
                  :type="type"
                  @click="() => showChoice(row)"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top"  v-if="row.purchaseStatus =='未审核'">
          <el-button
                  icon="el-icon-delete"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rowDel(row)"
                  v-if="permission.purchase_main_delete"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <purchase-form ref="purchaseForm" @success="refreshChange"></purchase-form>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, changeStatus,purReport, checkPurchaseByStock} from "@/api/anwise/purchase/purchase_main";
  import {userCompany} from "@/api/anwise/common";
  import { getDictionary } from '@/api/system/dictbiz';
  import {mapGetters} from "vuex";
  import purchaseForm from "./components/purchase_form.vue";

  export default {
      components: {purchaseForm},
      data() {
      return {
        form: {},
        query: {},
          search:{},
          purchaseDateRange:[],
        loading: true,
          dateFormat: 'YYYY-MM-DD',
          pickerOptions: {},
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
          typeDict:[],
        option: {
            height:'auto',
            calcHeight: 30,
            tip: false,
            searchShow: false,
            searchMenuSpan: 6,
            border: true,
            index: true,
            selection: true,
            reserveSelection:true,
            labelWidth: 150,
            searchLabelWidth:100,
            indexWidth:100,
            menuWidth: 210,
            addBtn: false,
            editBtn: false,
            viewBtn: false,
            delBtn: false,
            stripe: true,
            searchIndex: 3,
            searchIcon: false,
            searchEnter:true,
          column: [
            {
              label: "采购单号",
              prop: "idNo",
              type: "input",
                fixed: true,
                search: true,
                overHidden: true,
                sortable: true,
                width:180,
            },
            // {
            //   label: "所属机构账号",
            //   prop: "deptNo",
            //   type: "number",
            //   precision:0,
            //   min:0,
            //   controls:false,
            //   search: true,
            //   overHidden: true,
            //   sortable: true,
            //   width:150,
            // },
            {
              label: "所属机构名称",
              prop: "deptName",
              type: "input",
              search: true,
              overHidden: true,
              sortable: true,
              width:150,
            },
            {
              label: "供应商编号",
              prop: "supNo",
              type: "number",
                precision:0,
                min:0,
                controls:false,
                search: true,
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "供应商名称",
              prop: "supName",
              type: "input",
                search: true,
                overHidden: true,
                sortable: true,
                width:150,
            },
            // {
            //   label: "交货方式",
            //   prop: "deliMeth",
            //   type: "input",
            //     overHidden: true,
            //     sortable: true,
            //     width:120,
            // },
            {
              label: "交货地址",
              prop: "deliAddr",
              type: "input",
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "结算方式",
              prop: "payType",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "结算日期",
              prop: "payDate",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "采购类别",
              prop: "purchaseType",
              type: "input",
                search:true,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "要求送货日期",
              prop: "purchaseDate",
              type: "input",
                search: true,
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "税率",
              prop: "taxRate",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
                formatter:(val,value,label)=>{
                    if (value) {
                        return `${value}%VAT`
                    } else {
                        return ''
                    }
                },
            },
            {
              label: "币别",
              prop: "rmb",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "状态",
              prop: "purchaseStatus",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "审核人员",
              prop: "assign",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "审核时间",
              prop: "assignDate",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "备注",
              prop: "remark",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "创建人",
              prop: "createUserName",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,

            },

            {
              label: "创建时间",
              prop: "createTime",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.purchase_main_add, false),
          viewBtn: this.validData(this.permission.purchase_main_view, false),
          delBtn: this.validData(this.permission.purchase_main_delete, false),
          editBtn: this.validData(this.permission.purchase_main_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
      mounted() {
        this.initDict();
      },
    methods: {
      showChoice(row){
        purReport(row.id, this.isEnglish,this.hiddenBom).then(res => {
          if(res.data.success) {
            const file = res.data.data;
            // const originUrl = (file.url.replace(file.domain, `${this.res}/`));
            const url = file.url;
            // this.$refs.preview.open({
            //     url: url || "",
            //     originUrl: originUrl || ""
            // });
            console.log(url)
            window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
          }
        })
      },
      rowClassName({row, rowindex}) {
        if (row.purchaseStatus ==='未审核') {
          return 'row-yellow';
        }
      },
        rollbackAudit(row) {
            this.loading = true;
            checkPurchaseByStock(row).then(re=> {
                this.loading = false;
                if (re.data.success) {
                    changeStatus(row.id, 2).then(res => {
                        this.loading = false;
                        if (res.data.success) {
                            this.onLoad(this.page);
                            this.$message({
                                type: "success",
                                message: res.msg || "反审核成功!"
                            });
                        }
                    })
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        handleAudit(row) {
            this.loading = true;
            changeStatus(row.id, 1).then(res => {
                this.loading = false;
                if (res.data.success) {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: res.msg || "审核成功!"
                    });
                }
            }).catch(() => {
                this.loading = false;
            });
        },
        initDict() {
            getDictionary({code:'purchase_type'}).then(res => {
               if (res.data.success) {
                   this.typeDict = res.data.data;
               }
            });
        },
        handleView(row) {
            let title="查看采购单信息";
            let type='view';
            const id = row.id;
            this.$refs.purchaseForm.show({
                id,
                title,
                type
            })
        },
        handleEdit(row) {
            let title="采购单信息";
            let type='edit';
            const id = row.id;
            this.$refs.purchaseForm.show({
                id,
                title,
                type
            })
        },
        handleAdd() {
            userCompany().then(res => {
                if (res.data.success) {
                    this.dept = res.data.data;
                    if (!this.dept) {
                        this.$message({
                            type: "error",
                            message: "用户无组织机构信息，请联系安伟工作人员！"
                        });
                    } else {
                        let title="采购单信息";
                        let type='edit';
                        this.$refs.purchaseForm.show({
                            title,
                            type
                        })
                    }
                }
            })
        },
        sortChange(val) {
            console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoad(this.page);
        },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.search= {};
          this.purchaseDateRange = [];
          this.search.purchaseDateStart = '';
          this.search.purchaseDateEnd = '';
        this.onLoad(this.page);
      },
      searchChange(params, done) {
          this.query = params;
        // Object.assign(this.query, params)
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        handleDatePickerChange(value) {
          if (value) {
              this.search.purchaseDateStart = value[0];
              this.search.purchaseDateEnd = value[1];
          } else {
              this.search.purchaseDateStart = '';
              this.search.purchaseDateEnd = '';
          }
        },
    }
  };
</script>

<style>
</style>
